<?php
/**
* @file Digestm.php
* @synopsis  三级版主添加精品
* @author Yee, <rlk002@gmail.com>
* @version 1.0
* @date 2015年7月14日11:18:47
*/

defined('BASEPATH') OR exit('No direct script access allowed');

class Digestm extends CI_Model
{
	function __construct()
	{
		parent::__construct();
	}

	//更新帖子状态
	public function add_digest($post_id)
	{
		return $this->db->set("digest",1)->where("id",$post_id)->update("ml_post");
	}
    //取消精品
    public function cancel_digest($post_id)
    {
        return $this->db->set("digest",0)->where("id",$post_id)->update("ml_post");
    }

	/**
	 * 获取一条置顶帖id
	 * @param $post_type_extend
	 */
	public function get_top_post_id($post_type_extend)
	{
		$post_id = 0;
		if (!$post_type_extend) return $post_id;

		$key = TOP_POST_PREFIX.$post_type_extend;
		$post_id = $this->redis->get($key);
		if (is_bool($post_id) && $post_id == false) {
			$filter = array('post_type_extend' => $post_type_extend, 'is_show' => 1, 'type' => 1);
			$info = $this->db->select('post_id')->where($filter)->order_by('addtime', 'DESC')->get('ml_digest_log')->row_array();
			if (isset($info['post_id']) && $info['post_id']) {
				$post_id = $info['post_id'];
			} else {
				$post_id = 0;
			}

			$this->redis->save($key, $post_id, TOP_POST_KEY_EXPIRE_TIME);
		}

		return $post_id;
	}

	/**
	 * 随机获取用户的一篇推荐贴
	 * @param $post_type_extend
	 */
	public function get_recommend_post_id($user_id, $post_type_extend = 0)
	{
		$post_id = 0;
		$this->load->model('rssm');
		$rss_thread = $this->rssm->get_rss_thread($user_id);
		if (!$rss_thread) {
			$user_info  = $this->userm->getUserInfo($user_id);
			$rss_thread = array($user_info['thread']);
		}

		$curr_time = time();
		$filter = array('start_time <' => $curr_time, 'end_time >' => $curr_time, 'is_show' => 1, 'type' => 0);
		if (version_compare($this->softversion, "2.2.0") >= 0) {
			$filter['post_type_extend'] =  $post_type_extend;
		}

		$total = $this->db->select('post_id')->where($filter)->where_in('thread', $rss_thread)->count_all_results('ml_digest_log');
		if ($total) {
			$rand = mt_rand(0, $total - 1);
			$info = $this->db->select('post_id')->where($filter)->where_in('thread', $rss_thread)->order_by('id', 'DESC')->limit(1, $rand)->get('ml_digest_log')->row_array();
			if (isset($info['post_id']) && $info['post_id']) {
				$post_id = $info['post_id'];
			}
		}

		return $post_id;
	}
}

